﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Data.SqlClient;
using System.Reflection;
using System.Data;

namespace OgilvyOne.Utility
{
    public class SqlTool
    {
        private static StringBuilder sql = null;

        public static string buildInsertSql(object obj)
        {
            if (obj != null)
            {
                Type type = obj.GetType();
                PropertyInfo[] piArray = type.GetProperties();
                object value = null;
                sql = new StringBuilder(string.Format("insert {0} ( ", type.Name));
                StringBuilder valuesql = new StringBuilder(")values(");
                foreach (PropertyInfo pi in piArray)
                {
                    value = pi.GetValue(obj, null);
                    switch (pi.PropertyType.Name)
                    {
                        case "Int32":
                            if ((int)value > 0)
                            {
                                sql.Append(pi.Name);
                                valuesql.Append(value);
                                sql.Append(",");
                                valuesql.Append(",");
                            }
                            break;
                        case "String":
                            if (value != null)
                            {
                                sql.Append(pi.Name);
                                valuesql.Append(string.Format("'{0}'", value));
                                sql.Append(",");
                                valuesql.Append(",");
                            }
                            break;
                    }
                }
                sql.Remove(sql.ToString().LastIndexOf(','), 1).Append(valuesql.Remove(valuesql.ToString().LastIndexOf(','), 1).Append(");SELECT @@IDENTITY"));
            }
            return sql.ToString();
        }
    }
}
